<template>
  <div class="el-upload-model">
    <el-upload
      ref="upload"
      class="el-avatar-uploader"
      action="#"
      :multiple="multiple"
      :show-file-list="false"
      :http-request="handleUpload"
      :on-success="handleSuccess"
      list-type="picture-card"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>
<script>
import { uploadWhitelistInput } from '@/api/whitelistinput';
import { Loading } from 'element-ui';

export default {
  name: 'UploaExcel',
  props: {
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      newFile: new FormData(),
      base64: ''
    };
  },
  methods: {
    beforeUpload(file) {
      console.log(file)
      if (!(file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) {
        this.$message.error('导入的文件只能是.xls,.xlsx格式!');
        return false;
      }
      return true;
    },
    handleUpload(file) {
      this.newFile.append('file', file.file);
      let loadingInstance = Loading.service({ fullscreen: true });
      uploadWhitelistInput(this.newFile)
        .then(res => {
          loadingInstance.close();
          if (res.msg !== 'OK') {
            this.$message.error(res.msg);
          } else {
            this.$message.success('文件导入成功');
          }
          this.$refs.upload.clearFiles();
          this.$emit('uploadSuccess');
        });
    },
    handleRemove(file) {
      this.$refs.upload.abort();
    },
    handleSuccess(res, file) {
      this.$refs.upload.clearFiles();
      this.$emit('uploadSuccess');
    }
  }
};
</script>
